package com.liveneo.stoat.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

/**
 * 
 *@Description: 配置文件读取工具类
 *@Author:hjt 
 *@Since:2017年1月22日 下午3:36:49 
 *@Version:1.0.0
 */
public class PropertyUtil {

	private static final String DEFAULT_ENCODING = "UTF-8";
	private static Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
	private static PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();

	private static String fileName = "config.properties";
	private static Properties pt = null;
	
	public static final String SERVER_NAME;					//自动任务管理  服务器名称  测试数据
	
	static{
		pt = PropertyUtil.loadProperties(fileName);
		//查勘
		SERVER_NAME = pt.getProperty("SERVER_NAME");
	}
	
	
	/**
	 * 载入多个ClassPath中的properties文件, 相同的属性将会覆盖之前的载入.
	 * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
	 */
	public static Properties loadProperties(String... locations){
		Properties props = new Properties();
		try {
			for (String location : locations) {
				logger.debug("Loading properties file from classpath:" + location);
				InputStream is = null;
				try {
					Resource resource = new ClassPathResource(location);
					is = resource.getInputStream();
					propertiesPersister.load(props, new InputStreamReader(is, DEFAULT_ENCODING));
				} catch (IOException ex) {
					logger.info("Could not load properties from classpath:" + location + ": " + ex.getMessage());
				} finally {
					if (is != null) {
						is.close();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return props;
	}
}
